package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.Es.EsProd;
import com.bwie.Vo.PageProdVo;
import com.bwie.mapper.TbProdAttaMapper;
import com.bwie.mapper.TbTypeMapper;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbProdAtta;
import com.bwie.service.TbProdService;
import com.bwie.mapper.TbProdMapper;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @author 31803
* @description 针对表【tb_prod(商品表)】的数据库操作Service实现
* @createDate 2025-06-20 15:27:20
*/
@Service
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
    implements TbProdService{

    @Autowired
    HttpServletRequest request;
    @Autowired
    TbProdMapper tbProdMapper;

    @Autowired
    TbProdAttaMapper tbProdAttaMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public R ProdList(PageProdVo pageProdVo) {
        //构造分页参数
        Page<TbProd> page = new Page<>(pageProdVo.getPageNum(), pageProdVo.getPageSize());


        //分页查询
        Page<TbProd> tbProdPage = tbProdMapper.selectPageProd(page, pageProdVo);

        return R.ok().setData(tbProdPage);
    }

    @Override
    public R GetAddProd(TbProd tbProd) {
        TbProd tbProd1 = tbProdMapper.selectOne(
                new QueryWrapper<TbProd>()
                        .lambda()
                        .eq(TbProd::getProdSpu, tbProd.getProdSpu())
                        .or()
                        .eq(TbProd::getProdName,tbProd.getProdName())
        );
        if(tbProd1!=null){
            return R.erorr().setMsg("spu名称做重复或商品名称进行重复了");
        }
        String token = request.getHeader("token");
        if(token==null){
            return R.erorr().setMsg("用户请登录");
        }
        String userName = TokenUtils.getUserName(token);
        tbProd.setCreateBy(userName);
        tbProd.setCreateTime(new Date());
        tbProd.setProdStatus(0);
        tbProdMapper.insert(tbProd);

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R AddprodAtta(TbProdAtta tbProdAtta) {

        //1判断商品是否存在
        TbProd tbProd = tbProdMapper.selectById(
                tbProdAtta.getProdId()
        );
        if(tbProd==null){
            return R.erorr().setMsg("商品不存在");
        }



        //2删除原有附件
        tbProdAttaMapper.delete(
                new QueryWrapper<TbProdAtta>().lambda().eq(TbProdAtta::getProdId, tbProdAtta.getProdId())
        );

        //3添加附件
        String token = request.getHeader("token");
        if(token==null){
            return R.erorr().setMsg("用户未登录");
        }
        String userName = TokenUtils.getUserName(token);
        tbProdAtta.setCreateBy(userName);
        tbProdAtta.setCreateTime(new Date());
        tbProdAttaMapper.insert(tbProdAtta);


        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteBatchProd(List<Integer> ids) {

        //1批量删除
        tbProdMapper.deleteBatchIds(ids);
        //2批量删除商品附件
        tbProdAttaMapper.delete(
                new QueryWrapper<TbProdAtta>()
                        .lambda().in(TbProdAtta::getProdId,ids)
        );


        return R.ok();
    }

    @Override
    public R deleteProd(Integer prodId) {

        //1判断商品是否存在
        TbProd tbProd = tbProdMapper.selectOne(
                new QueryWrapper<TbProd>()
                        .lambda().eq(TbProd::getProdId, prodId)
        );
        //2删除商品
        tbProdMapper.deleteById(prodId);
        return R.ok();
    }

    @Override
    public R getProdToEs(PageProdVo pageProdVo) {
        //1构造分页条件
        Integer pageNum=0;
        if(pageProdVo.getPageNum()>0){
            pageNum=pageProdVo.getPageNum()-1;
        }
        PageRequest page = PageRequest.of(pageNum, pageProdVo.getPageSize());
        //2构造查询条件
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        if(StringUtils.isNotEmpty(pageProdVo.getKeyWord())){
            queryBuilder.must(QueryBuilders.matchQuery("prodName",pageProdVo.getKeyWord()));
            queryBuilder.must(QueryBuilders.matchQuery("brandName",pageProdVo.getKeyWord()));
        }
        if(pageProdVo.getStatusId()!=null){
            queryBuilder.must(QueryBuilders.termQuery("prodStatus",pageProdVo.getStatusId()));
        }
        if(StringUtils.isNotEmpty(pageProdVo.getBeginTime())&&StringUtils.isNotEmpty(pageProdVo.getEndTime())){
            queryBuilder.must(QueryBuilders.rangeQuery("createTime").format("yyyy-MM-dd HH:mm:ss").timeZone("GMT+8").from(pageProdVo.getBeginTime()).to(pageProdVo.getEndTime()));
        }


        FieldSortBuilder prodId = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder prodName = highlightBuilder.field("brandName").field("prodName").preTags("<font color='red'>").postTags("</font>");
        //3开始查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(queryBuilder).withPageable(page).withHighlightBuilder(prodName).withSort(prodId);
        SearchHits<EsProd> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProd.class);
        List<SearchHit<EsProd>> searchHits = search.getSearchHits();
        long totalHits = search.getTotalHits();
        HashMap<String, Object> map = new HashMap<>();

        ArrayList<EsProd> esProds = new ArrayList<>();
        //4返回查询结果
        for (SearchHit<EsProd> searchHit : searchHits) {
            EsProd es = searchHit.getContent();
            List<String> brandName = searchHit.getHighlightField("brandName");
            List<String> prodName1 = searchHit.getHighlightField("prodName");
            if(prodName1!=null&&prodName1.size()>0){
                for (String s : prodName1) {
                    es.setProdName(s);
                }
            }
            if(brandName!=null&&brandName.size()>0){
                for (String s1 : brandName) {
                    es.setBrandName(s1);
                }
            }
            esProds.add(es);
        }
        map.put("total",totalHits);
        map.put("records",esProds);
        return R.ok().setData(map);
    }
}




